package com.diankangwo.factory.controller;

import com.diankangwo.common.utils.PageUtils;
import com.diankangwo.common.utils.Query;
import com.diankangwo.common.utils.R;
import com.diankangwo.factory.dto.TdDistributionDTO;
import com.diankangwo.factory.dto.TdUserInfoDTO;
import com.diankangwo.factory.entity.TdDistribution;
import com.diankangwo.factory.entity.TdOrder;
import com.diankangwo.factory.entity.TdPort;
import com.diankangwo.factory.entity.TdUserinfo;
import com.diankangwo.factory.service.TdDistributionService;
import com.diankangwo.factory.service.TdOrderService;
import com.diankangwo.factory.service.TdPortService;
import com.diankangwo.factory.service.TdUserInfoService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 分销管理（佣金明细Controller）
 * Created by wuye on 2017/10/17.
 */
@RestController
@RequestMapping("/fac/dbc")
public class TdDistributionController {

    @Autowired
    private TdDistributionService tdDistributionService;

    @Autowired
    private TdUserInfoService tdUserInfoService;

    @Autowired
    private TdPortService tdPortService;

    @Autowired
    private TdOrderService tdOrderService;

    /**
     * 分销排行
     *
     * @return
     */
    @ApiOperation(value = "获取分销排行列表", notes = "")
    @ApiImplicitParam(name = "params", value = "查询条件", required = true, dataType = "Map<String,Object>")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @RequiresPermissions("fac:dbc:list")
    public R queryByList(@RequestParam Map<String, Object> params) {
        //查询列表数据
        try{
            Query query = new Query(params);
            List<TdUserinfo> userList = tdUserInfoService.queryList3(query);
            int total = tdUserInfoService.queryTotal3(query);
            List<TdDistributionDTO> dtoList = new ArrayList<>();
            for (int i = 0; i < userList.size(); i++) {
                int prizeuserid = userList.get(i).getId();
                List<TdDistribution> tdDistributionList = tdDistributionService.queryByprizeuserid(prizeuserid);
                TdDistributionDTO dto = new TdDistributionDTO();
                //用户个人
                dto.setUserinfo(userList.get(i));
                //端口
                List<TdPort> tdPortList = tdPortService.queryByUserId(prizeuserid);
                dto.setPortList(tdPortList);
                //推荐人
                int parentUserId = userList.get(i).getParentid();
                if(parentUserId != 0){
                    TdUserinfo tdUserinfo = tdUserInfoService.queryById(parentUserId);
                    dto.setTriggerUserName(tdUserinfo.getUsername());
                }
                //客户数量
                int parentId = prizeuserid;
                List<TdUserinfo> userinfos = tdUserInfoService.queryByParentId2(parentId);
                if (userinfos.size() > 0) {
                    dto.setCustomerNum(userinfos.size());
                } else {
                    dto.setCustomerNum(0);
                }
                //累计佣金
                float accumulateMoney = (tdDistributionService.queryByPrizeuseSumMoney(prizeuserid) == null ? 0 : tdDistributionService.queryByPrizeuseSumMoney(prizeuserid));
                //已结算佣金
                float payMoney = (tdDistributionService.queryByPrizeusePayMoney(prizeuserid) == null ? 0 : tdDistributionService.queryByPrizeusePayMoney(prizeuserid));
                //未结算佣金
                float unsettledMoney = 0;
                if (accumulateMoney > payMoney) {
                    unsettledMoney = (accumulateMoney - payMoney);
                } else {
                    unsettledMoney = 0;
                }
                dto.setCumulativeMoney(accumulateMoney);
                dto.setSettlementMoney(payMoney);
                dto.setUnliquidatedMoney(unsettledMoney);
                dtoList.add(dto);
            }
            PageUtils pageUtil = new PageUtils(dtoList, total, query.getLimit(), query.getPage());
            return R.ok().put("page", pageUtil);
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }

    }


    /**
     * 查看推荐人详情
     *
     * @return
     */
    @ApiOperation(value = "查看推荐人详情", notes = "")
    @ApiImplicitParam(name = "parentid", value = "推荐人ID", required = true, dataType = "Integer")
    @RequestMapping(value = "/queryParentUser", method = RequestMethod.POST)
    @RequiresPermissions("fac:dbc:queryParentUser")
    public R queryParentUser(int parentId) {
        TdUserinfo userinfo = tdUserInfoService.queryById(parentId);
        if (userinfo != null) {
            userinfo.setPassword("");
        }
        return R.ok().put("userinfo", userinfo);
    }


    /**
     * 查看客服列表
     *
     * @return
     */
    @ApiOperation(value = "查看推荐人详情", notes = "")
    @ApiImplicitParam(name = "clientlist", value = "推荐人ID", required = true, dataType = "Integer")
    @RequestMapping(value = "/clientlist", method = RequestMethod.POST)
    @RequiresPermissions("fac:dbc:clientlist")
    public R clientlist(int parentId) {
        List<TdUserInfoDTO> tdUserInfoDTOS = new ArrayList<>();
        List<TdUserinfo> userinfo = tdUserInfoService.queryByParentId2(parentId);
        for (int i = 0; i < userinfo.size(); i++) {
            TdUserInfoDTO tdUserInfoDTO = new TdUserInfoDTO();
            tdUserInfoDTO.setUserinfo(userinfo.get(i));
            List<TdOrder> tdOrders = tdOrderService.queryByUid(userinfo.get(i).getUid());
            int total = 0;
            for (int j = 0; j < tdOrders.size(); j++) {
                total += tdOrders.get(j).getTotalfee();
            }
            tdUserInfoDTO.setSumMoney(total);
            tdUserInfoDTOS.add(tdUserInfoDTO);
        }
        return R.ok().put("tdUserInfoDTOS", tdUserInfoDTOS);
    }


    /**
     * 查看会员基本信息
     */
    @ApiOperation(value = "查看会员基本信息", notes = "")
    @ApiImplicitParam(name = "params", value = "筛选条件", required = true, dataType = "Map<String,Object>")
    @RequestMapping(value = "/queryUserInfo", method = RequestMethod.POST)
    @RequiresPermissions("fac:dbc:queryUserInfo")
    public R queryUserInfo(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        List<TdUserinfo> userinfoList = tdUserInfoService.queryByParentId(query);
        int total = tdUserInfoService.queryTotal2(query);
        List<TdUserInfoDTO> tdUserInfoDTOList = new ArrayList<>();
        for (int i = 0; i < userinfoList.size(); i++) {
            TdUserInfoDTO dto = new TdUserInfoDTO();
            userinfoList.get(i).setPassword("");
            dto.setUserinfo(userinfoList.get(i));
            List<TdOrder> tdOrderList = tdOrderService.queryByUid(userinfoList.get(i).getUid());
            int sumMoney = 0;
            for (int j = 0; j < tdOrderList.size(); j++) {
                sumMoney += tdOrderList.get(j).getTotalfee();
            }
            dto.setSumMoney(sumMoney/100);
            tdUserInfoDTOList.add(dto);

        }
        PageUtils pageUtil = new PageUtils(tdUserInfoDTOList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看基本信息
     */
    @ApiOperation(value = "查看基本信息", notes = "")
    @ApiImplicitParam(name = "userid", value = "会员ID", required = true, dataType = "Integer")
    @RequestMapping(value = "/queryInfo", method = RequestMethod.POST)
    @RequiresPermissions("fac:dbc:queryInfo")
    public R queryInfo(int userid) {
        TdUserinfo userinfo = tdUserInfoService.queryById(userid);
        userinfo.setPassword("");
        return R.ok().put("user", userinfo);
    }

    /**
     * 查看佣金详情
     */
    @ApiOperation(value = "查看佣金详情", notes = "")
    @ApiImplicitParam(name = "params", value = "参数", required = true, dataType = "Map<String,Object>")
    @RequestMapping(value = "/queryCommissionDetails", method = RequestMethod.POST)
    @RequiresPermissions("fac:dbc:queryCommissionDetails")
    public R queryCommissionDetails(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        List<TdDistribution> tdDistributionList = tdDistributionService.queryList2(query);
        int total = tdDistributionService.queryTotal2(query);
        PageUtils pageUtil = new PageUtils(tdDistributionList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }
}
